package com.yincai.carefreewater.usb;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


import com.yincai.carefreewater.tool.ToastTool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Created by ${zhangke} on 2017/7/20.
 */

public class UsbTool {
    private static final String TAG ="tag" ;
    private static UsbManager mUsbManager;
    private static UsbTool tool;
    private Context context;
    ProlificSerialDriver    driver = null;
    public static   UsbTool getInstance(){
        if (tool == null) {
            tool = new UsbTool();
        }
        return tool;
    }
    private UsbTool (){}
    private Handler handler;
    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public void openUsbDevice(Context context){
        this.context=context;

        ifRegist();
        tryGetUsbPermission(context);
    }

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    private void tryGetUsbPermission(Context context){
        try {
            mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
            //here do emulation to ask all connected usb device for permission
            Collection<UsbDevice> values = mUsbManager.getDeviceList().values();
            Iterator<UsbDevice> iterator = values.iterator();
            List<UsbDevice> list=new ArrayList<>();
            while (iterator.hasNext()){
                UsbDevice next = iterator.next();
                Log.i(TAG, "tryGetUsbPermission: "+next.getProductId());
                list.add(next);

            }
            if(list.size()>0){

                UsbDevice usbDevice = list.get(list.size()-1);
                if(mUsbManager.hasPermission(usbDevice)){
                    //if has already got permission, just goto connect it
                    //that means: user has choose yes for your previously popup window asking for grant perssion for this usb device
                    //and also choose option: not ask again
                    afterGetUsbPermission(usbDevice);

                    //   Log.i(TAG, "tryGetUsbPermission: "+handler);

                }else{
                    //this line will let android popup window, ask user whether to allow this app to have permission to operate this usb device
                    mUsbManager.requestPermission(usbDevice, mPermissionIntent);
                }
            }

        }catch (Exception e){
           e.printStackTrace();
        }

    }


    private void afterGetUsbPermission(UsbDevice usbDevice){
      //  ToastTool.toast("Got permission for usb device: " + usbDevice);
     //   ToastTool.toast("Found USB device: VID=" + usbDevice.getVendorId() + " PID=" + usbDevice.getProductId());
//        Log.i(TAG, "afterGetUsbPermission: "+"Got permission for usb device: " + usbDevice+"=========Found USB device: VID=" + usbDevice.getVendorId() + " PID=" + usbDevice.getProductId());

        doYourOpenUsbDevice(usbDevice);
    }

    private void doYourOpenUsbDevice(UsbDevice usbDevice){

        try {
            if(usbDevice == null){
                ToastTool.toast("设备是空的");
                return ;
            }else{
                Log.i(TAG, "doYourOpenUsbDevice: "+usbDevice);
                 driver = new ProlificSerialDriver(context, usbDevice);
                driver.setup(19200);
               readFromUsb(driver);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if(th!=null) {
                th.setFlag(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private  void ifRegist(){
        Intent intent = new Intent();
        intent.setAction(ACTION_USB_PERMISSION);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent,0);
        if(resolveInfos != null && !resolveInfos.isEmpty()){
            //查询到相应的BroadcastReceiver
            Log.i(TAG, "ifRegist: "+"查到");
        }else {
            Log.i(TAG, "ifRegist: "+"未知");
        }

    }


    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "onReceive: "+action);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        //user choose YES for your previously popup window asking for grant perssion for this usb device
                        if(null != usbDevice){
                            afterGetUsbPermission(usbDevice);
                        }
                    } else {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                      //  ToastTool.toast("Permission denied for device" + usbDevice);
                      //  Log.i(TAG, "onReceive: ---"+ "Permission denied for device" + usbDevice);
                        if(th!=null){
                        th.setFlag(false);
                        }
                        tryGetUsbPermission(context);

                    }
                }
            }
        }
    };

    /**
     * 读取线程一直读取
     */
    private  usbThresd th;

    public void readFromUsb(ProlificSerialDriver driver){
        th=new usbThresd();

        th.start();
    }

    public class  usbThresd  extends  Thread{

        private  boolean  flag=true;

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            try {
                while(flag){
                   // Log.i(TAG, "run: " +flag);
                    if(handler==null){
                        handler=getHandler();
                    }
                    read(driver);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }

    /**
     * @throws IOException
     * 读取数据
     *
     */
    public void read(ProlificSerialDriver driver) throws IOException {
        Message msg=null;
     if(handler!=null){

           msg=handler.obtainMessage();
     }
        try {
            byte[] data = driver.read();
//			if(data.length == 0){
//                msg.what=0;
//                msg.obj="没读到数据";
//				handler.sendMessage(msg);
//				return ;
//			}
            if(data.length>0){
//
              //  Log.i(TAG, "read:--- "+ hexStr2Str(data));
              //  String message = HexDump.dumpHexString(data);
                String message =hexStr2Str(data);
              // Log.i("tag", "read: "+message);
                if(handler!=null){
                    msg.what=1;
                    msg.obj=message;
                    handler.sendMessage(msg);
                }
            }else {

               // Log.i("tag", "read: "+data.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(handler!=null){
                msg.obj="出现异常了"+e.getMessage();
                msg.what=-1;
                handler.sendMessage(msg);
            }
        }
    }
    /***
     * 给平板写数据
     *
     *
     */

    public void  writeToUsb(byte[] data){
        Message msg=null;
        if(handler!=null){
            msg=handler.obtainMessage();
        }
        try{
            driver.write(data, data.length);
        }catch (Exception e){
            e.printStackTrace();
            if(handler!=null){
                msg.obj="没有连接设备"+e.getMessage();
                msg.what=-1;
                handler.sendMessage(msg);
            }
        }
    }
    public void  unRegist(){
        if(mUsbPermissionActionReceiver!=null){
            try {
                context.unregisterReceiver(mUsbPermissionActionReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param b
     * @return
     *
     * 字节数组转 16进制
     */
    private   String byte2hex(byte b[]) {
        if (b == null) {
            throw new IllegalArgumentException(
                    "Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     *
     * @return
     * 16转字符串
     */
    private String hexStr2Str(byte b[])
    {
        String hexStr  =byte2hex(b);

        String str = "0123456789ABCDEF";
        String news="";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++)
        {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        news=new  String(bytes);
        return news;
    }



}
